/* 
 * @(#)GlideWindow.java    Created on 2012-9-12
 * Copyright (c) 2012 ZDSoft Networks, Inc. All rights reserved.
 * $Id$
 */
package bjxg.test.thread;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author chengcy
 * @version $Revision: 1.0 $, $Date: 2012-9-12 下午4:11:32 $
 */
public class GlideWindow extends Thread {
    private int size = 10;
    private final Map todo = new LinkedHashMap();
    private final Map wait = new HashMap();

    public GlideWindow() {
        start();
        // try{
        // Thread.sleep( 100 );
        // }
        // catch ( InterruptedException ex ){
        // ex.printStackTrace();
        // }
    }

    @Override
    public void run() {
        synchronized (this) {
            for (;;) {
                while (wait.size() >= size || todo.size() == 0) {
                    try {
                        this.wait();
                    }
                    catch (InterruptedException ignored) {
                    }
                }

                Object key = todo.keySet().iterator().next();
                Runnable job = (Runnable) todo.remove(key);
                wait.put(key, job);
                System.out.println("put to wait " + key);
                job.run();
            }
        }
    }

    public synchronized void addJob(Object key, Runnable job) {
        System.out.println("add " + key);
        todo.put(key, job);
        notifyAll();
    }

    public synchronized Object remove(Object key) {
        System.out.println("remove " + key);
        notifyAll();
        return wait.remove(key);
    }

    public void setSize(int size) {
        this.size = size;
    }

    public int getSize() {
        return size;
    }

    public static void main(String[] args) {
        GlideWindow glideWindow = new GlideWindow();
        glideWindow.setSize(10); // 窗口大小

        // 以下10个任务都被执行,都是没有回应
        for (int i = 0; i < 10; i++) {
            glideWindow.addJob(new Integer(i), new Runnable() {
                @Override
                public void run() {
                    System.out.println("task running");
                }
            });
        }

        // 窗口已满,"waiting"这个任务不会执行,处于等待状态
        glideWindow.addJob("waiting", new Runnable() {
            @Override
            public void run() {
                System.out.println("task running");
            }
        });

        // 对0任务作出回应,"waiting"这个任务可以执行了
        glideWindow.remove(new Integer(0));
    }
}
